package com.baima;

/**
 * @author ck
 * @date 2021/9/8 19:13
 */

import com.baima.mapper.UserMapper;
import com.baima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Mybatis  代理开发
 */
public class MyBatisDemo2 {

    public static void main(String[] args) throws IOException {
//        method1();

        int id = 1;
        //1、加载mybatis核心配置文件、获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);


        //2、获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();


        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.selectById(id);
        System.out.println(user);
    }

    private static void method1() throws IOException {
        //1、加载mybatis核心配置文件、获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);


        //2、获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3、执行sql语句
//        List<User> users = sqlSession.selectList("test.selectAll");
        //3.1 获取UserMapper接口的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.selectAll();
        //4、打印
        System.out.println(users);

        //5、释放资源
        sqlSession.close();
    }
}
